package cn.message.web;

import cn.itcast.pojo.classsify;
import cn.itcast.pojo.image;
import cn.itcast.util.OutputStringController;
import cn.message.service.ImageService;
import cn.web.web_module.util.IconPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author 郭智超
 * @create 2020-05-15 9:32
 */
@Slf4j
@RestController
@RequestMapping(value="/dhn/message",produces="text/html;charset=UTF-8")
public class ImageController {

    @Resource
    private ImageService imageService;

    @Resource
    private OutputStringController osc;

    @RequestMapping("/getAllImage")
    @ResponseBody
    public String getAllImage(@RequestBody Map<String,String> map){
        String results = "";
        Map<String, Object> resultMap = imageService.getAllImage(map);
        //获取所有的图片
        Object imageList = resultMap.get("imageList");
        //获取总记录数
        int count = (int)resultMap.get("count");
        if(imageList == null){
            results = osc.resultFailure("查询所有图片信息失败", "");
            log.debug("查询所有图片信息失败");
        }
        else {
            results = osc.resultSuccess("查询所有帮助中心信息成功",imageList, count);
            log.debug("查询所有图片信息成功");
        }
        return results;
    }

    @ResponseBody
    @PostMapping(value = "/addImage",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addImage(HttpServletRequest request,
                                  @RequestParam(value = "imageType",required = false) String imageType,
                                  @RequestParam(value = "image",required = false) MultipartFile icon){
        String results = "";
        log.debug(imageType);
        if(imageType.isEmpty()){
            return osc.failure("图片类型不能为空，请选择图片类型");
        }
        if(icon == null){
            return osc.failure("图片不能为空，请上传图片");
        }

        image image = new image();
        image.setImageType(imageType);

        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/image/";//松注解

        String iconPath = IconPath.ICONPATH +"icon/image/";
//        String iconPathEnum = "E:/job/testIconPath";
        FileOutputStream fos = null;
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
//        image.setImagePath("http://120.79.51.10:8181/dhn/icon/image/"+iconName);
        image.setImagePath("https://www.dhnep.cn:8181/dhn/icon/image/"+iconName);
//        image.setImagePath("E:/job/testIconPath"+iconName);
        Boolean aBoolean = imageService.addImage(image);
        if (!aBoolean) {
            results = osc.failure("添加失败");
        } else {
            results = osc.success("添加成功");
        }
        return results;
    }

    @ResponseBody
    @PostMapping(value = "/updateImage",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateImage(HttpServletRequest request,
                           @RequestParam(value = "imageType",required = false) String imageType,
                           @RequestParam(value = "id",required = false) Integer id ){

        String results = "";
        image image = new image();
        image.setImageType(imageType);
        image.setId(id);

        Boolean aBoolean = imageService.updateImage(image);
        if (!aBoolean) {
            results = osc.failure("修改失败");
        } else {
            results = osc.success("修改成功");
        }
        return results;
    }

    /**
     * 修改图片信息时，图片立即上传的接口
     * @param request
     * @param icon
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/uploadPicture",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String uploadPicture(HttpServletRequest request,
                             @RequestParam(value = "image",required = false) MultipartFile icon,
                             @RequestParam(value = "id",required = false) Integer id){
        System.out.println("开始上传图片了-----------------------------------------------------------");
        String results="";
        if(icon.isEmpty()){
            return osc.failure("图片为空，请上传图片");
        }
        if(id == null || id.equals("")){
            return osc.failure("id为空");
        }
        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/image/"; //松注释

        String iconPath = IconPath.ICONPATH+"icon/image/";

//        String iconPathEnum = "E:/job/testIconPath/";
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        //设置新文件名称（包含格式）
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }

        image image = new image();
        image.setId(id);
//        image.setImagePath("http://120.79.51.10:8181/dhn/icon/image/"+iconName);
        image.setImagePath("https://www.dhnep.cn:8181/dhn/icon/image/"+iconName);
//        image.setImagePath("E:/job/testIconPath"+iconName);
        Boolean aBoolean = imageService.updateImage(image);
        if (!aBoolean) {
            results = osc.failure("图片上传失败");
        } else {
            results = osc.success("图片上传成功");
        }
        return results;
    }

    @RequestMapping("/deleteImage")
    @ResponseBody()
    public String deleteImage(@RequestBody Map<String,String> map){
        String results = "";
        int id = Integer.parseInt(map.get("id"));
        Boolean aBoolean = imageService.deleteImage(id);
        if (!aBoolean) {
            results = osc.failure("删除失败");
        } else {
            results = osc.success("删除成功");
        }
        return results;
    }


    @ResponseBody
    @PostMapping(value = "/uploadlicense",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addImagelicense(HttpServletRequest request,
                           @RequestParam(value = "imageType",required = false) String imageType,
                           @RequestParam(value = "image",required = false) MultipartFile icon){
        String results = "";
        log.debug(imageType);
        if(imageType.isEmpty()){
            return osc.failure("图片类型不能为空，请选择图片类型");
        }
        if(icon == null){
            return osc.failure("图片不能为空，请上传图片");
        }

        image image = new image();
        image.setImageType(imageType);

        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/image/";//松注解

        String iconPath = IconPath.ICONPATH +"icon/image/";
//        String iconPathEnum = "E:/job/testIconPath";
        FileOutputStream fos = null;
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
//        image.setImagePath("http://120.79.51.10:8181/dhn/icon/image/"+iconName);
        image.setImagePath("https://www.dhnep.cn:8181/dhn/icon/image/"+iconName);
//        image.setImagePath("E:/job/testIconPath"+iconName);
        Boolean aBoolean = imageService.addImage(image);
        if (!aBoolean) {
            results = osc.failure("添加失败");
        } else {
            results = osc.success("添加成功");
        }
        return results;
    }





}
